﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using JESAI.MQTT.Client.Clients;
using JESAI.MQTT.Client.Configurations;
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Internal;
using MQTTnet.Protocol;
using MQTTnet.Server;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JESAI.MQTT.Client.ServiceCollections
{
    public static class ServiceCollectionExtensions
    {

        public static void UseJESAIMqttClient(this IApplicationBuilder app, IConfiguration Configuration)
        {

        }

        public static IServiceCollection AddJESAIMQTTClient(this IServiceCollection services, IConfiguration Configuration)
        {
            string hostIp = Configuration["MqttClientOption:HostIp"];//IP地址
            int hostPort = int.Parse(Configuration["MqttClientOption:HostPort"]);//端口号
            int timeout = int.Parse(Configuration["MqttClientOption:Timeout"]);//超时时间

            string password = Configuration["MqttClientOption:Password"];//IP地址

            string username = Configuration["MqttClientOption:UserName"];//IP地址

            MQTTClientConfig mQTTClientConfig = new MQTTClientConfig();
            mQTTClientConfig.Port = hostPort;
            mQTTClientConfig.Server = hostIp;
            mQTTClientConfig.Password = password;
            mQTTClientConfig.UserName = username;
            mQTTClientConfig.TimeOut = timeout;

            MQTTClient mQTTClient = new MQTTClient(mQTTClientConfig);

                mQTTClient.ApplicationMessageReceivedAsync += delegate (MqttApplicationMessageReceivedEventArgs args)
                {
                    // Do some work with the message...

                    // Now respond to the broker with a reason code other than success.
                    args.ReasonCode = MqttApplicationMessageReceivedReasonCode.ImplementationSpecificError;
                    args.ResponseReasonString = "That did not work!";
                    Console.WriteLine(args.ApplicationMessage.Topic);
                    // User properties require MQTT v5!

                    // Now the broker will resend the message again.
                    return Task.CompletedTask;
                };
            mQTTClient.AddSubsctibeHandle();

            return services;
        }


    }
}
